package com.fwj.user.dao.rbac;

import com.fwj.user.entity.rbac.role.RBACRelationUserAndRole;
import org.apache.ibatis.annotations.Select;
import tk.mybatis.mapper.common.Mapper;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

/**
* @author root
* @description 针对表【rbac_relation_user_role】的数据库操作Mapper
* @createDate 2022-05-01 17:08:11
* @Entity domain.domain.RbacRelationUserRole
*/
public interface RBACRelationUserAndRoleMapper extends Mapper<RBACRelationUserAndRole> {

    /**
     * 根据userID查询用户具有的角色
     * */
    @Select(value = "SELECT " +
            "id, " +
            "user_id userId, " +
            "role_id roleId, " +
            "creator, " +
            "create_time createTime, " +
            "update_time updateTime, " +
            "status " +
            "FROM rbac_relation_user_role " +
            "WHERE " +
            "1 = 1 " +
            "AND user_id = #{userId} " +
            "AND status = #{status} " +
            "ORDER BY id")
    List<RBACRelationUserAndRole> findRoleListByUserId(Long userId, String status);

    /**
     * 根据roleId递归查询用户是否具有该角色或父角色
     * */
    @Select(value = "" +
            "SELECT " +
            "id " +
            "FROM rbac_relation_user_role " +
            "WHERE " +
            "user_id = #{userId} " +
            "AND role_id IN ( " +
            "SELECT " +
            "r2.role_id " +
            "FROM " +
            "( SELECT @r AS _id, " +
            "( SELECT @r := parent_id FROM rbac_role WHERE role_id = _id) AS parent_id, " +
            "@l := @l + 1 AS lvl " +
            "FROM ( SELECT @r := #{roleId} , @l := 0) vars, " +
            "rbac_role r " +
            "WHERE @r <> 0 " +
            ") r1 " +
            "JOIN rbac_role r2 " +
            "ON r1._id = r2.role_id " +
            "ORDER BY r1.lvl DESC " +
            ")"
    )
    List<RBACRelationUserAndRole> findAllFatherRoleByParentIdByUserId(Long userId, Long roleId);

}




